<script lang="ts" setup>
import Motion from "@/utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
import { bg, avatar, illustration } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";
import QrCode from '@/components/ReQrCode'
import * as dd from "dingtalk-jsapi";
import {scanCodeLogin} from "@/api/user";

defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const loginType = ref(0)

const { initStorage } = useLayout();
initStorage();

const { dataTheme, overallStyle, dataThemeChange } = useDataThemeChange();
dataThemeChange(overallStyle.value);
const { title } = useNav();

const qrUrl = 'https://login.dingtalk.com/oauth2/auth?client_id=dingy2bevlzbymxviqnk&scope=openid&state=dddd&response_type=code&redirect_uri=https://oa.huiyanjd.com/station-web/#/login&prompt=consent'

const ruleForm = reactive({
  username: "admin",
  password: "admin123"
});

// const createQrCode = ()=>{
//   window.DTFrameLogin(
//     {
//       id: 'ding_qrCode',
//       width: 480,
//       height: 400,
//     },
//     {
//       redirect_uri: encodeURIComponent('https://oa.huiyanjd.com/base-station/api/v1/dingtalk/login/scanCode/in'),
//       client_id: 'ding7ubzkglwqdhtsfhw',
//       scope: 'openid',
//       response_type: 'code',
//       state: Date.now(),
//       prompt: 'consent',
//     },
//     async loginResult => {
//       console.log('登录成功--->', loginResult)
//       const { redirectUrl, authCode, state } = loginResult
//       const res = await scanCodeLogin(authCode)
//       console.log(res)
//     },
//     errorMsg => {
//       console.log(errorMsg,1)
//     }
//   )
// }
// onMounted(()=>{
//   createQrCode()
// })
const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      loading.value = true;
      useUserStoreHook()
        .loginByUsername({ username: ruleForm.username, password: "admin123" })
        .then(res => {
          if (res.success) {
            // 获取后端路由
            return initRouter().then(() => {
              router.push(getTopMenu(true).path).then(() => {
                message("登录成功", { type: "success" });
              });
            });
          } else {
            message("登录失败", { type: "error" });
          }
        })
        .finally(() => (loading.value = false));
    }
  });
};

  /** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (["Enter", "NumpadEnter"].includes(code)) {
    onLogin(ruleFormRef.value);
  }
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <div class="select-none">
    <img :src="bg" alt="." class="wave" />
    <div class="flex-c absolute right-5 top-3">
      <!-- 主题 -->
      <el-switch
        v-model="dataTheme"
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        inline-prompt
        @change="dataThemeChange"
      />
    </div>
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <avatar class="avatar" />
          <Motion>
            <h2 class="outline-none">{{ title }}</h2>
          </Motion>

<!--          账号密码登录-->
          <el-form
            v-if="loginType === 0"
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入账号',
                    trigger: 'blur'
                  }
                ]"
                prop="username"
              >
                <el-input
                  v-model="ruleForm.username"
                  :prefix-icon="useRenderIcon(User)"
                  clearable
                  placeholder="账号"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password">
                <el-input
                  v-model="ruleForm.password"
                  :prefix-icon="useRenderIcon(Lock)"
                  clearable
                  placeholder="密码"
                  show-password
                />
              </el-form-item>
            </Motion>

            <Motion :delay="250">
              <el-button
                :loading="loading"
                class="w-full mt-4"
                size="default"
                type="primary"
                @click="onLogin(ruleFormRef)"
              >
                开始演示
              </el-button>
            </Motion>
          </el-form>
<!--钉钉扫码登录-->
          <div v-if="loginType === 1" id="login_qrCode" class="login_qrCode">
            <Motion :delay="100">
              <div id="ding_qrCode" class="ding_qrCode"></div>
<!--              <QrCode :text="qrUrl" :width="150" logo="https://img.alicdn.com/imgextra/i4/O1CN01vxJvXB1eIQrLGMbLm_!!6000000003848-2-tps-1717-1717.png" />-->
              <div class="qr_tip">请使用钉钉扫码登录</div>
            </Motion>
          </div>
          <Motion>
            <div class="login_type">
              <div v-if="loginType === 1" class="type_item" @click="loginType = 0">账号密码登录</div>
              <div v-if="loginType === 0" class="type_item" @click="loginType = 1">钉钉扫码登录</div>
            </div>
          </Motion>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}

.qr_tip {
  font-size: 1.3vh;
  color: #999;
}

.login_type {
  width: 100%;
  padding: 0 1vh;
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;

  .type_item {
    cursor: pointer;
    font-size: 1.3vh;
    color: #2196f3;
  }
}
</style>
